package test;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import javax.sound.midi.Soundbank;

public class ServerMqtt {
    public static final String HOST = "tcp://wblink.tpddns.cn:8083";
    //public static final String HOST = "http://wblink.tpddns.cn:18083";
    //定义一个主题
    public static final String TOPIC = "testtopic/#";
    public static final String TOPIC125 = "topic125";
    //定义MQTT的ID，可以在MQTT服务配置中指定
    private static final String clientid = "mqttjs_0dccb8f1c5";

    private MqttClient client;
    private MqttTopic topic11;
    private MqttTopic topic125;
    private MqttMessage message;

    /**
     * 构造函数
     * @throws MqttException
     */
    public ServerMqtt() throws Exception{

        // MemoryPersistence设置clientid的保存形式，默认为以内存保存
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        connect();

        System.out.println("走了？");
    }

    private void connect(){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName("admin");
        options.setPassword("public".toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new PushCallback());
            System.out.println("options = " + options);
            client.connect(options);
            topic11 = client.getTopic(TOPIC);
            System.out.println("topic11 : " + topic11);
            topic125 = client.getTopic(TOPIC125);
        }catch (MqttSecurityException e){
            e.printStackTrace();
            System.out.println("MqttSecurityException");
        }catch (MqttException e){
            e.printStackTrace();
            System.out.println("MqttException");
        }


    }

    public void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException,MqttException{
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println("消息发布。" + token.isComplete());
    }

    public static void main(String[] args) throws Exception {
        ServerMqtt server = new ServerMqtt();
        server.message = new MqttMessage();
        server.message.setQos(1);
        server.message.setRetained(true);
        System.out.println("topic11" + server.topic11);
        server.message.setPayload("给客户端11推送的消息--------------《《《《《为了区别》》》》我是客户端11".getBytes());
        server.publish(server.topic11 , server.message);
        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("给客户端125推送的信息，我是客户端125".getBytes());
        server.publish(server.topic125 , server.message);
        System.out.println(server.message.isRetained() + "------ratained状态");
    }
}
